<?php
class Model_MapperCommentaire implements Model_IMapper
{
	private $table = null;
	
	public function __construct($str_table, $pdo)
	{
		$this->table = new Model_TableCommentaire();
		$this->table->setConnexion($pdo);
		$this->table->init();
	}
	
	public function getAll()
	{
		$results = array();
		foreach($this->table->fetchAll() as $ligne)
		{
			$entity = new Model_Commentaire();
			$entity->setId_commentaire($ligne['id_commentaire']);
			$entity->setContenu($ligne['contenu']);
			$entity->setDate_commentaire($ligne['date_commentaire']);
			
			//recupere l'association
			$associationmap = new Model_MapperAssociation("association", $this->table->getConnexion());
			$association = $associationmap->getOne($ligne['id_association']);
			
			if(!is_null($association))
				$entity->setAssociation($association);
				
			//recupere l'evenement
			$evenementmap = new Model_MapperEvenement("evenement", $this->table->getConnexion());
			$evenement = $evenementmap->getOne($ligne['id_evenement']);
			
			if(!is_null($evenement))
				$entity->setEvenement($evenement);
					
			$results[] = $entity;
		}
		return $results;
	}
	
	public function getOne($id)
	{
		$ligne = $this->table->fetchOne($id);
		if(!empty($ligne['id_evenement']) )
		{
						$entity = new Model_Commentaire();
			$entity->setId_commentaire($ligne['id_commentaire']);
			$entity->setContenu($ligne['contenu']);
			$entity->setDate_commentaire($ligne['date_commentaire']);
			
			//recupere l'association
			$associationmap = new Model_MapperAssociation("association", $this->table->getConnexion());
			$association = $associationmap->getOne($ligne['id_association']);
			
			if(!is_null($association))
				$entity->setAssociation($association);
				
			//recupere l'evenement
			$evenementmap = new Model_MapperEvenement("evenement", $this->table->getConnexion());
			$evenement = $evenementmap->getOne($ligne['id_evenement']);
			
			if(!is_null($evenement))
				$entity->setEvenement($evenement);
		}
		else 
		{
			$entity = null;
		}
		return $entity;
	}
	
	public function save(Model_IEntity $object)
	{
		if($object->getId_commentaire() == -1)
		{
			$id = $this->table->insert(
				$object->getContenu(),
				$object->getDate_commentaire(),
				$object->getAssociation()->getId_association(),
				$object->getEvenement()->getId_evenement()
			);
			$object->setId_commentaire($id);
		}
		else
		{
			$this->table->update(
				$object->getId_commentaire(),
				$object->getContenu(),
				$object->getDate_commentaire(),
				$object->getAssociation()->getId_association(),
				$object->getEvenement()->getId_evenement()
			);
		}
	}
	
	public function delete(Model_IEntity $object)
	{
		$this->table->delete($object->getId_commentaire());
	}
}